<?php

require_once dirname(__FILE__) . '/../lib/programGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/programGeneratorHelper.class.php';

/**
 * program actions.
 *
 * @package    sf_sandbox
 * @subpackage program
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class programActions extends autoProgramActions {

    public function executeCopy(sfWebRequest $request) {
        $id = $this->getRequestParameter('id');
        $this->redirect('program/new?copy_id=' . $id);
    }

    public function executeType(sfWebRequest $request) {
        if ($request->hasParameter('type')) {
            switch ($request->getParameter('type')) {
                case 'day':
                    $this->getUser()->setAttribute('program_type', 'day');
                    $this->redirect('program/index');
                    break;
                case 'night':
                    $this->getUser()->setAttribute('program_type', 'night');
                    $this->redirect('program/index');
                    break;
            }
        }
    }

    public function executeLong_term(sfWebRequest $request) {
        
    }

    public function executeListShow(sfWebRequest $request) {
        $id = $this->getRequestParameter('id');
        $this->program = ProgramTable::getInstance()->find($id);

        $this->form = new ProgramForm($this->program);

        unset($this->form['created_by_user_id'], $this->form['updated_by_user_id'], $this->form['code_sector_list']
        );
    }

    public function executeNew(sfWebRequest $request) {
        $this->form = $this->configuration->getForm();
        $this->program = $this->form->getObject();

        if ($this->getRequestParameter('copy_id')) {
            $copy_id = $this->getRequestParameter('copy_id');
            $item = ProgramTable::getInstance()->find($copy_id);
            $item_arr = $item->toArray();
            unset($item_arr['id'], $item_arr['created_at'], $item_arr['updated_at'], $item_arr['created_by_user_id'], $item_arr['updated_by_user_id']);
            $this->program = new Program();
            $this->program->fromArray($item_arr);

            $this->form = new ProgramForm($this->program);
        }
    }

    public function executeAssignments(sfWebRequest $request) {
        $program_id = $this->getRequestParameter('id');

        //WHAT THE HELL!!! not working
        $this->redirect('@assignment_filter?link_teacher_program_filters[program_id]=' . $program_id);
    }

    // needs more organizing !
    public function executeAttendance(sfWebRequest $request) {
        $program_id = $this->getRequestParameter('id');
        $program_obj = ProgramTable::getInstance()->find($program_id);
        $this->program_name = $program_obj->getName();
        $fname = $program_obj->getName() . ' - ' . I18nUtilities::__('Attendance') . '.doc';
        $link_q = LinkTeacherProgramTable::getInstance()->getQueryByStatus(LinkTeacherProgramTable::STATUS_APPROVED);
        $link_q->leftJoin('ltp.Teacher t');
        $link_q->addWhere('ltp.program_id = ?', $program_id);
        $this->teachers = $link_q->fetchArray();
        $this->days = $program_obj->getPeriod();
        $this->days = array_chunk($this->days, 5);
        $html = $this->getPartial('attendance');
        header('Content-type: application/doc');
        header('Content-Disposition: attachment; filename="' . $fname . '"');
        header('Content-Description: File Transfer');
//        header("Content-Length: " . strlen($html));
        echo globals::wordify($html);
        exit;
    }

    public function executeListTeachers(sfWebRequest $request) {
        $program_id = $this->getRequestParameter('id');
        $program_obj = ProgramTable::getInstance()->find($program_id);
        $link_q = LinkTeacherProgramTable::getInstance()->getQueryByStatus(LinkTeacherProgramTable::STATUS_APPROVED);
        $link_q->leftJoin('ltp.Teacher t');
        $link_q->addWhere('ltp.program_id = ?', $program_id);
        $link_q->leftJoin('t.Attendance a');
        $this->teachers = $link_q->fetchArray();
    }

    public function executeAttendanceFill(sfWebRequest $request) {

        $program_id = $this->program_id = $this->getRequestParameter('id');
        $program_obj = ProgramTable::getInstance()->find($program_id);
        $this->program_name = $program_obj->getName();
        
        if ($request->isMethod('POST')) {
            $data = $request->getParameter('attendance');
            AttendanceTable::getInstance()->createQuery()->delete()->where('program_id = ?', $program_id)->execute();
         
            foreach ($data as $k => $one) {
                $pid = explode('x', $k);
                $obj = new Attendance();
                $obj->setProgramId($program_id);
                $obj->setTeacherId($pid[1]);
                $obj->setDate($pid[0]);
                $obj->setClassShift($pid[2]);
                try {
                    $obj->save();
                } catch (Exception $e) {
                    
                }
            }
        }

        $program_obj = ProgramTable::getInstance()->find($program_id);
        $fname = $program_obj->getName() . ' - ' . I18nUtilities::__('Attendance') . '.doc';
        $link_q = LinkTeacherProgramTable::getInstance()->getQueryByStatus(LinkTeacherProgramTable::STATUS_APPROVED);
        $link_q->leftJoin('ltp.Teacher t');
        $link_q->addWhere('ltp.program_id = ?', $program_id);
        $link_q->leftJoin('t.Attendance a');

        $this->teachers = $link_q->fetchArray();
        $this->days = $program_obj->getPeriod();
        $this->absences = AttendanceTable::getInstance()->createQuery()->where('program_id = ?', $program_id)->fetchArray();
    }

    public function executeCertificates(sfWebRequest $request) {
        $program_id = $this->program_id = $this->getRequestParameter('id');
        $this->program_obj = ProgramTable::getInstance()->find($program_id);
        $this->program_name = $this->program_obj->getName();
        $link_q = LinkTeacherProgramTable::getInstance()->getQueryByStatus(LinkTeacherProgramTable::STATUS_APPROVED);
        $link_q->leftJoin('ltp.Teacher t');
        $link_q->addWhere('ltp.program_id = ?', $program_id);
        $link_q->leftJoin('t.School s');
        $link_q->leftJoin('t.Attendance a');
        $this->teachers = $link_q->fetchArray();
    }

    public function executeExport_certificates(sfWebRequest $request) {
        $program_id = $this->program_id = $this->getRequestParameter('id');
        $this->program_obj = ProgramTable::getInstance()->find($program_id);
        $this->program_name = $this->program_obj->getName();
        $teachers = $request->getParameter('give_cert');

        $this->manager_name = $request->getParameter('manager_name');
        $this->center_name = $request->getParameter('center_name');

        $ids = array();
        foreach ($teachers as $k => $one) {
            $ids[] = $k;
        }

        if (count($ids))
            $this->teachers = TeacherTable::getInstance()
                    ->createQuery('t')
                    ->whereIn('intg_identity', $ids)
                    ->leftJoin('t.School s')
                    ->fetchArray();
        $this->setLayout('popupLayout');
    }

    public function executeSendConfirmSms(sfWebRequest $request) {
        $id = $this->getRequestParameter('id');
        $program = ProgramTable::getInstance()->find($id);

        $this->forward404Unless($program);

        $q = $program->getAcceptedTeachersQuery();
        $q->select('t.id')->addSelect('t.mobile');

        $accpeted_teachers = $q->fetchArray();

        $phone_arr = array();
        foreach ($accpeted_teachers as $s_teacher) {
            $phone_arr[] = sfConfig::get('app_mobile_prefix', '00966') .$s_teacher['mobile'];
        }
        $msg_text = str_replace('%%program_name%%', $program->getName(), I18nUtilities::__('TEACHER_APPROVE_SMS_MSG'));
        $msg_text = str_replace('%%program_location%%', is_numeric($program->getLocationOfHolding()) ? $program->getLocationsInSector()->getExtendedString() : $program->getLocationOfHolding(), $msg_text);
        $msg_text = str_replace('%%start_date%%', globals::getHijreeDate($program->getStartDate()), $msg_text);
        $msg_text = str_replace('%%end_date%%', globals::getHijreeDate($program->getEndDate()), $msg_text);
        globals::send_sms($msg_text, $phone_arr);

        $program->setSendApproved(true);
        $this->getUser()->setFlash('notice', sprintf(I18nUtilities::__('SMS was sent to teachers accepted in program %s'), $program->__toString()));

        $this->redirect('program/index');
    }

    /**
     * override the default buildQuery() method to add filtering by editor sector functionality
     * @return Doctrine_query
     */
    protected function buildQuery() {
        $query = parent::buildQuery();
        if ($this->getUser()->hasCredential('SUPERVISOR_ADMIN')) {
            $sectors = $this->getUser()->getGuardUser()->getSectors();
            $ids = array();
            foreach ($sectors as $one)
                $ids[] = $one->get('intg_id');

            if (is_array($ids) && count($ids) > 0) {
                $query->innerJoin('r.CodeSector sec');
                $query->whereIn('sec.intg_id', $ids);
            }
        }

        $hc = new hijreeConvertor();
        $my_date = $hc->GregorianToIslamic2(time());
        $query->orderBy("IF(start_date >= '$my_date', DATEDIFF('$my_date', start_date), -1*start_date) desc");
        return $query;
    }

    public function executeExport(sfWebRequest $request) {
        $q = parent::buildQuery();

        $q->select('
            name
            , CONCAT(t.f_name," ",t.s_name," ",t.l_name) as trainer_name
            , duration_days
            , start_date
            , end_date
            , loc.name as location
            , sector.name as sector
            , is_mandatory
            '
        );

        $q->leftJoin('r.Trainer as t');
        $q->leftJoin('r.LocationsInSector as loc');
        $q->leftJoin('r.CodeSector as sector');
        //     $q->leftJoin('r.CodeTarget as target');

        $items = $q->fetchArray();

        $order = array(
            'name'
            , 'trainer_name'
            , 'is_mandatory'
            , 'duration_days'
            , 'start_date'
            , 'end_date'
            , 'location'
            , 'sector'
                //   , 'target'
        );

        $labels = array(
            'name' => 'Program name'
            , 'trainer_name' => 'Trainer'
            , 'duration_days' => 'Duration days'
            , 'start_date' => 'Start date'
            , 'end_date' => 'End date'
            , 'location' => 'Location'
            , 'sector' => 'Sector'
            , 'is_mandatory' => 'Is mandatory'
                //  , 'target' => 'Target'
        );

        $partial = $this->getPartial('teacher/export', array('items' => $items, 'order' => $order, 'labels' => $labels));

        $word = globals::wordify($partial);

        header('Content-type: application/doc');
        header('Content-Disposition: attachment; filename="programs_list_' . (substr(time(), 0, 5)) . '.doc"');
        header('Content-Description: File Transfer');

        die($word);
    }

    public function executeSendCustomSms(sfWebRequest $request) {
        $this->setLayout('popupLayout');
        $this->id = $this->getRequestParameter('id');
        $this->program = ProgramTable::getInstance()->find($this->id);

        $this->forward404Unless($this->program);
        $this->send_succ = false;

        $q = $this->program->getAcceptedTeachersQuery();
        $this->teacher_count = $q->count();
        if (!$this->teacher_count)
            return;
        $this->form = new programTeachersSmsForm(null, array('program' => $this->program));
        if ($request->isMethod('POST')) {
            $data = $this->getRequestParameter($this->form->getName());
            $this->form->bind($data);

            if ($this->form->isValid()) {
                $values = $this->form->getValues();
                foreach ($values['mobile_numbers'] as $mob){
                    $phone_arr[] = sfConfig::get('app_mobile_prefix', '00966') .$mob;
                }
                globals::send_sms($values['sms_body'], $phone_arr);

                $this->send_succ = true;
            }
        }
    }

}
